import { v4 as uuidv4 } from 'uuid';

const vscode = acquireVsCodeApi();

export function webViewPostMessage(eventName:string, data?:any, cb?:Function) {
  const uuid = uuidv4();
  const key = `${eventName}__${uuid}`;
  /** 以 node 形式发送，解决 webview 跨域问题 */

  vscode.postMessage({
    type: key,
    payload: data,
  });

  const callback = (event:any) => {
    const { data } = event;

    if (data.type === key) {
      cb?.(data.payload);
      window.removeEventListener('message', callback);
    }
  };

  window.addEventListener('message', callback);
}


export default vscode;

